from django.shortcuts import render
from user.models import User,Department,Duty,Staff
from user.serializers import DeparSer,DutySer,StaffSer
from rest_framework.views import APIView
from rest_framework.response import Response
import re
# from rest_framework.generics import
# from rest_framework.viewsets import ModelViewSet



# Create your views here.
class CheckUsername(APIView):
    def get(self,request,username):
        if not re.findall(r'^[a-zA-Z]\w{4,15}$',username):
            return Response({'code':204,'msg':'用户名格式不对'})
        if User.objects.filter(username=username):
            return Response({'code':204,'msg':'用户名重复'})
        return Response({'code':200,'msg':'OK'})

# class CheckMobile(APIView):
#     def get(self,request,mobile):
#         if not re.findall(r'^1[3-9]\d{9}$',mobile):
#             return Response({'code':204,'msg':'手机号格式不对'})
#         return Response({'code':200,'msg':'OK'})
class CheckPassword(APIView):
    def post(self,request):
        password = request.data.get('password')
        if not re.findall(r'^\w{6,15}$',password):
              return Response({'code':400,'msg':"密码格式错误"})
        else:
            return Response({'code':200,'msg':'ok',})


class Register(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')

        if not all([username,password]):
            return Response({'code':204,'msg':'注册信息不完整'})
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code':400,'msg':'用户存在'})
        User.objects.create(username=username,password=password)
        return Response({'code':200,'msg':'注册成功'})

# import jwt # datetime
# from gaoziyang import settings
# # 生成jwt token
# def generate_jwt_token(user):
#     # 要加密的数据 字典
#     payload = {
#         'id':user.id,
#         'username':user.username,
#     }
#     # 进行加密，生成jwt token
#     token = jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
#     # 返回token
#     return token
class Login(APIView):
    def post(self,request):
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        try:
            # 3.判断用户是否存在
            from django.db.models import Q
            user = User.objects.get(Q(username=username)| Q(mobile=username))
        except Exception as e:
            print(e)
            return Response({'code':204,'msg':'用户不存在'})
        # 4.判断密码是否正确
        # if  not user.check_password(password):
        if not user.password == password:
            return Response({'code':204,'msg':'用户名或密码错误'})
        # 5.密码正确
        # 生成用户的jwt token
        # token = generate_jwt_token(user)
        return Response({
            'code':200,
            'msg':"用户%s登录成功"%user.username,
            # 'token':token,
            # 'user':{
            #     'userName':user.username,
            #     'uid':user.id
            # }
        })

class DepartmentView(APIView):
    def get(self,request):
        department_list = Department.objects.all()
        ser = DeparSer(department_list,many=True)
        return Response({'code':200,'department':ser.data})

    def post(self, request):
        # 接收网页发送的数据
        name = request.data.get('name')
        # 获取部门对象，用来判断部门是否存在
        department_obj = Department.objects.filter(name=name)
        # 判断部门是否存在，如果存在，返回部门存在
        if department_obj:
            return Response({'msg': '部门存在', 'code': 400})
        # 不存在时，反序列化添加部门
        dep_serializer = DeparSer(data=request.data)
        # 校验
        if dep_serializer.is_valid():
            # 校验通过，保存数据
            dep_serializer.save()
            # 返回
            return Response({'msg': '添加成功', 'code': 200})
        # 校验失败，返回错误消息
        else:
            return Response({'error': dep_serializer.errors, 'code': 400})

class DutyView(APIView):
    def get(self,request):
        Duty_list = Duty.objects.all()
        ser = DutySer(Duty_list,many=True)
        return Response({'code':200,'duty':ser.data})

class StaffView(APIView):
    def get(self,request):
        Staff_list = Staff.objects.all()
        ser = StaffSer(Staff_list,many=True)
        return Response({'code':200,'staff_list':ser.data})

class AddDeparView(APIView):
    def post(self, request):
        ser = DeparSer(data=request.data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg':'添加数据成功'}, status=201)
        return Response({'msg': '添加数据失败'}, status=500)

class AddDutyView(APIView):
    def post(self, request):
        ser = DutySer(data=request.data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg':'添加数据成功'}, status=201)
        return Response({'msg': '添加数据失败'}, status=500)

